package map;

import java.io.FileNotFoundException;
import java.util.ArrayList;

import util.FileOperation;

/**
 * 
 * @Title: CandyBSTMap.java 
 * @Package map 
 * @Description: 基于二分搜索树的映射实现
 * @author CandyWall   
 * @date 2021年1月6日 下午4:34:39 
 * @version V1.0
 */
public class CandyBSTMap<K extends Comparable<K>, V> implements CandyMap<K, V> {
    private class Node {
        public K key;
        public V value;
        
        public Node left, right;
        
        public Node(K key, V value) {
            this.key = key;
            this.value = value;
            this.left = null;
            this.right = null;
        }
    }
    
    private Node root;
    private int size;
    
    public CandyBSTMap() {
        root = null;
        size = 0;
    }

    @Override
    public void add(K key, V value) {
        root = add(root, key, value);
    }
    // 向以node为根的二分搜索树中插入元素(key, value)，递归算法
    // 返回插入新节点后的二分搜索树的根
    private Node add(Node node, K key, V value) {
        if(node == null) {
            size++;
            return new Node(key, value);
        }
        if(key.compareTo(node.key) < 0) {
            node.left = add(node.left, key, value);
        }
        else if(key.compareTo(node.key) > 0) {
            node.right = add(node.right, key, value);
        }
        else { // key.compareTo(node.key) == 0
            node.value = value;
        }
        return node;
    }

    @Override
    public V remove(K key) {
        Node node = getNode(root, key);
        if(node == null) {
            return null;
        }
        root = remove(root, key);
        return node.value;
    }
    
    // 删除掉以node为根的二分搜索树中键为key的节点，递归算法
    // 返回删除节点后新的二分搜索树的根
    private Node remove(Node node, K key) {
        if(node == null) {
            return null;
        }
        if(key.compareTo(node.key) < 0) {
            node.left = remove(node.left, key);
            return node;
        }
        else if(key.compareTo(node.key) > 0) {
            node.right = remove(node.right, key);
            return node;
        } else {
            // 如果左子树为空
            if(node.left == null) {
                Node rightNode = node.right;
                node.right = null;
                size--;
                return rightNode;
            }
            // 如果右子树为空
            if(node.right == null) {
                Node leftNode = node.left;
                node.left = null;
                size--;
                return leftNode;
            }
            // 如果左右子树都不为空
            // 寻找当前节点右子树的最小的元素所在的节点
            Node successor = findMin(node.right);
            successor.right = removeMin(node.right);
            successor.left = node.left;
            node.left = node.right = null;
            return successor;
        }
    }
    
    // 删除掉以node为根的二分搜索树中的最小节点
    private Node removeMin(Node node) {
        // 如果已经是最左边的元素了
        if(node == null) {
            Node rightNode = node.right;
            node.right = null;
            size--;
            return rightNode;
        }
        // 不是最左边的元素，继续去左子树删
        node.left = removeMin(node.left);
        return node;
    }
    
    // 寻找以node为根的二分搜索树的最小元素：递归实现
    private Node findMin(Node node) {
        if(node.left == null) {
            return node;
        }
        return findMin(node.left);
    }

    @Override
    public boolean contains(K key) {
        return getNode(root, key) != null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(root, key);
        return node == null ? null : node.value;
    }
    
    private Node getNode(Node node, K key) {
        if(node == null) {
            return null;
        }
        if(key.compareTo(node.key) < 0) {
            return getNode(node.left, key);
        } else if(key.compareTo(node.key) > 0) {
            return getNode(node.right, key);
        } else {
            return node;
        }
    }

    @Override
    public void set(K key, V newValue) {
        Node node = getNode(root, key);
        if(node == null) {
            throw new RuntimeException("待修改的元素不存在");
        }
        node.value = newValue;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }
    
    public void printMap() {
        inOrderPrint(root);
    }
    
    // 中序遍历打印映射中的键和值
    private void inOrderPrint(Node node) {
        if(node == null) {
            return;
        }
        inOrderPrint(node.left);
        System.out.println("key=" + node.key + ", value=" + node.value);
        inOrderPrint(node.right);
    }
    
    // 完成词频统计，返回每个单词和对应出现的次数
    public static CandyBSTMap<String, Integer> wordCount(ArrayList<String> words) {
        CandyBSTMap<String, Integer> wordCountMap = new CandyBSTMap();
        for(String word : words) {
            // 如果映射中不包含这个单词，说明这个单词第1次出现，
            // 那么将这个单词添加到映射中
            if(!wordCountMap.contains(word)) {
                wordCountMap.add(word, 1);
            } else {
                wordCountMap.set(word, wordCountMap.get(word) + 1);
            }
        }
        return wordCountMap;
    }
    
    // 从文件中读取到所有的单词，并以ArrayList<String>方式返回
    private static ArrayList<String> readWordsFromFile(String filePath) {
        ArrayList<String> words = new ArrayList<>();
        if(!FileOperation.readFile(filePath, words)) {
            // 加载失败
            try {
                throw new FileNotFoundException("找不到文件");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } 
        return words;
    }
    
    public static void main(String[] args) {
        ArrayList<String> list = readWordsFromFile("testData/pride-and-prejudice.txt");
        CandyBSTMap<String, Integer> wordCountMap = wordCount(list);
        wordCountMap.printMap();
        System.out.println("单词总数：" + list.size());
        System.out.println("不同单词数量：" + wordCountMap.getSize());
        System.out.println("pride出现的次数：" + wordCountMap.get("pride"));
        System.out.println("prejudice出现的次数：" + wordCountMap.get("prejudice"));
    }
}
